package com.detection.common.utils;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson2.JSON;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class CacheFileUtils {
    private static Map<String,Object> cacheMap = new HashMap<>(16);
    private static String filePath =null;
    public static void initCacheFile(String filePath) throws IOException {
        CacheFileUtils.filePath = filePath ;
        File cacheFile = new File(filePath);
        if(!cacheFile.getParentFile().exists()){
            cacheFile.getParentFile().mkdirs();
        }
        if(!cacheFile.exists()){
            cacheFile.createNewFile();
        }
        String cacheFileStr = FileUtil.readString(cacheFile,"utf-8");
        if("".equals(cacheFileStr)){
            writeStringToFile();
            return;
        }
        CacheFileUtils.cacheMap =JSON.parseObject(cacheFileStr);
    }

    public static Object getCache(String key){
        return CacheFileUtils.cacheMap.get(key);
    }

    public static void setCache(String key,String value){
        if(CacheFileUtils.cacheMap.containsKey(key)){
            CacheFileUtils.cacheMap.remove(key);
        }
        CacheFileUtils.cacheMap.put(key,value);
        writeStringToFile();
    }
    private static void writeStringToFile(){
        FileUtil.writeString(JSON.toJSONString(cacheMap),CacheFileUtils.filePath,"utf-8");
    }
}
